package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.business.entity.BaseBusiness;
import com.mrd.gtimp.business.entity.Booking;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Contacter;
import com.mrd.gtimp.business.entity.Container;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.GoodAddress;
import com.mrd.gtimp.business.entity.Goods;
import com.mrd.gtimp.business.entity.Trail;
import com.mrd.spring.repository.BaseRepository;

import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


@Service
public class BusinessBiz1 extends BaseBiz<BaseBusiness> {

    @Resource
    private BookingBiz bookingBiz;
    @Resource
    private GoodsBiz goodsBiz;
    @Resource
    private ContainerBiz containerBiz;

    @Resource
    private TrailBiz trailBiz;
    @Resource
    private GoodAddressBiz goodAddressBiz;
    @Resource
    private AttachmentBiz attachmentBiz;

    @Resource
    private DeclarationBiz declarationBiz;
    @Resource
    private CommodityBiz commodityBiz;

    @Resource
    private ContacterBiz contacterBiz;

    public void saveAllBizData(Booking booking, Trail trail, Declaration declaration)
            throws Exception {
        WebApplicationContext wc = WebApplicationContextUtils
                .getWebApplicationContext(HttpUtils.getServletContext());
        // save booking
        saveBooking(booking);

        // save trail
        saveTrail(trail);

        // save declaration
        // declare is always not null
        saveDeclaration(declaration);
    }

    public void updateAllBizData(Booking booking, Trail trail, Declaration declaration)
            throws Exception {
        // updateBooking(booking);
    }

    /**
     * 保存修改的订舱信息
     */
    private void updateBooking(Booking booking) throws Exception {
        // 删除原先的货物
        /*
         * List<Goods> goods = goodsBiz
		 * .findEntityByHql("from com.mrd.gtimp.business.pojo.Goods where booking.id='"
		 * + booking.getId() + "'", 0, 10, null);
		 * if(null != goods && goods.size() > 0) {
		 * for(Goods g : goods) {
		 * goodsBiz.delete(g);
		 * }
		 * }
		 * // 添加修改后的货物
		 * for(Goods g : booking.getGoodses()) {
		 * goodsBiz.saveOrupdateEntity(g);
		 * }
		 */

        // 保存修改后的订舱信息
        List<Booking> books = new ArrayList<Booking>();
        books.add(booking);
        // bookingBiz.saveOrupdateEntity(booking);
        bookingBiz.saveOrUpdateEntities(books);
    }

    /**
     * 保存数据中未保存（unsaved状态）的联系人
     */
    private void saveOrUpdateContacter(Contacter contacter, Company customer, String creator)
            throws Exception {
        if (contacter != null) {
            if (null == contacter.getId() || "".equals(contacter.getId())) {
                contacter.setId(null);
                contacter.setOwner(customer);
                contacter.setCREATOR(creator);
                contacter.setCTIME(new Date());
                contacterBiz.saveOrupdateEntity(contacter);
            }
        }
    }

    /**
     * 保存修改报关业务信息
     */
    private void saveDeclaration(Declaration declaration) throws Exception {
        if (null != declaration && null != declaration.getCommodities()) {
            saveOrUpdateContacter(declaration.getShipper(), declaration.getCustomer(), declaration.getCreator());
            declarationBiz.saveOrupdateEntity(declaration);
            for (Commodity commodity : declaration.getCommodities()) {
                if (null == commodity.getDeclaration()) {
                    commodity.setDeclaration(declaration);
                }
                commodityBiz.saveOrupdateEntity(commodity);
            }
        }
    }

    /**
     * 保存修改拖车业务信息
     */
    private void saveTrail(Trail trail) throws Exception {
        if (null != trail) {
            if (trail.getSoDoc() != null
                    && (trail.getSoDoc().getId() == null || trail.getSoDoc().getId().equals(""))) {
                attachmentBiz.saveOrupdateEntity(trail.getSoDoc());
            }
            saveOrUpdateContacter(trail.getShipper(), trail.getCustomer(), trail.getCreator());
            trailBiz.saveOrupdateEntity(trail);
            // reinit ct_gaddress
            StringBuffer ctIdBuffer = new StringBuffer();
            Map<String, Container> persisCTMap = new HashMap<String, Container>();
            for (GoodAddress goodAddress : trail.getGdes()) {
                if (null == goodAddress.getTrail()) {
                    goodAddress.setTrail(trail);
                }
                for (Container c : goodAddress.getContainers()) {
                    if (ctIdBuffer.indexOf(c.getId()) == -1) {// 未保存的柜
                        String cid = c.getId();
                        ctIdBuffer.append(cid + ",");
                        c.setId(null);
                        containerBiz.saveOrupdateEntity(c);
                        persisCTMap.put(cid, c);
                    } else {
                        c.setId(persisCTMap.get(c.getId()).getId());
                    }
                }
                saveOrUpdateContacter(goodAddress.getContacter(), trail.getCustomer(), trail.getCreator());
                goodAddressBiz.saveOrupdateEntity(goodAddress);
            }
        }
    }

    /**
     * 保存修改订舱业务信息
     */
    private void saveBooking(Booking booking) throws Exception {
        if (null != booking) {
            saveOrUpdateContacter(booking.getShipper(), booking.getCustomer(), booking.getCreator());
            saveOrUpdateContacter(booking.getConsignee(), booking.getCustomer(), booking.getCreator());
            bookingBiz.saveOrupdateEntity(booking);
            for (Goods goods : booking.getGoodses()) {
                if (null == goods.getBooking()) {
                    goods.setBooking(booking);
                }
                goodsBiz.saveOrupdateEntity(goods);
            }
        }
    }

    public void setBaseRepository(BaseRepository<BaseBusiness, String> baseRepository) {
        super.baseRepository = baseRepository;
    }
}
